package com.example.managemyself;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.appcompat.widget.Toolbar;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.ui.auth.LoginActivity;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.util.ThemeManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;

/**
 * 主活动类 - 用户登录后的主界面
 * 负责管理底部导航和Fragment切换
 * 
 * @author ManageMyself Team
 * @version 1.0
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    
    // 导航相关常量
    private static final int[] TOP_LEVEL_DESTINATIONS = {
        R.id.navigation_tasks,
        R.id.navigation_diary, 
        R.id.navigation_home,
        R.id.navigation_ai_chat,
        R.id.navigation_profile
    };
    
    // UI组件
    private AppBarConfiguration appBarConfiguration;
    private NavController navController;
    private Toolbar toolbar;
    private BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 应用主题（必须在setContentView之前）
        applyCurrentTheme();
        
        super.onCreate(savedInstanceState);
        
        try {
            // 修复数据库版本冲突问题
            fixDatabaseIssues();
            
            // 检查用户登录状态
            if (!checkUserLoginStatus()) {
                return; // 如果未登录，直接返回
            }
            
            // 初始化任务完成通知器
            initializeTaskCompletionNotifier();
            
            // 初始化UI
            initializeUI();
            
            // 设置导航
            setupNavigation();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in onCreate: " + e.getMessage(), e);
            // 发生错误时跳转到登录页面
            redirectToLogin();
        }
    }

    /**
     * 应用当前主题
     */
    private void applyCurrentTheme() {
        try {
            ThemeManager themeManager = ThemeManager.getInstance(this);
            themeManager.applyTheme();
            Log.d(TAG, "Theme applied: " + themeManager.getThemeModeName());
        } catch (Exception e) {
            Log.e(TAG, "Error applying theme", e);
        }
    }

    /**
     * 修复数据库相关问题
     */
    private void fixDatabaseIssues() {
        try {
            Log.i(TAG, "检查数据库状态...");
            
            // 尝试获取数据库实例，如果失败则重新创建
            AppDatabase.getInstance(this);
            
            Log.i(TAG, "数据库状态正常");
        } catch (Exception e) {
            Log.w(TAG, "数据库存在问题，尝试修复: " + e.getMessage());
            
            // 检查是否是迁移错误
            if (e.getMessage() != null && e.getMessage().contains("duplicate column")) {
                Log.w(TAG, "检测到列重复错误，使用专门的修复方法");
                handleDatabaseMigrationError();
            } else {
                // 普通数据库错误处理
                handleGeneralDatabaseError();
            }
        }
    }
    
    /**
     * 处理数据库迁移错误
     */
    private void handleDatabaseMigrationError() {
        try {
            // 导入数据库修复工具
            com.example.managemyself.util.DatabaseRepairHelper.repairDatabaseMigrationError(this);
            Log.i(TAG, "数据库迁移错误修复完成");
        } catch (Exception e) {
            Log.e(TAG, "数据库迁移错误修复失败", e);
            // 如果专门修复失败，使用强制重建
            handleGeneralDatabaseError();
        }
    }
    
    /**
     * 处理一般数据库错误
     */
    private void handleGeneralDatabaseError() {
        try {
            // 清理数据库实例
            AppDatabase.clearInstance();
            
            // 删除旧数据库文件
            deleteDatabase("manage_myself_db");
            
            // 重新创建数据库
            AppDatabase.getInstance(this);
            
            Log.i(TAG, "数据库重建完成");
        } catch (Exception fixError) {
            Log.e(TAG, "数据库重建失败", fixError);
            // 显示错误提示
            showToast("数据库初始化失败，请重启应用");
        }
    }

    /**
     * 检查用户登录状态
     * @return true if logged in, false otherwise
     */
    private boolean checkUserLoginStatus() {
        UserManager userManager = UserManager.getInstance();
        if (userManager == null || !userManager.isLoggedIn()) {
            Log.i(TAG, "User not logged in, redirecting to login");
            redirectToLogin();
            return false;
        }
        
        Log.i(TAG, "User logged in: " + userManager.getCurrentUser().getUsername());
        return true;
    }

    /**
     * 重定向到登录页面
     */
    private void redirectToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    /**
     * 初始化UI组件
     */
    private void initializeUI() {
        setContentView(R.layout.activity_main);
        
        // 设置Toolbar
        toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        } else {
            Log.w(TAG, "Toolbar not found in layout");
        }

        // 获取底部导航视图
        bottomNavigationView = findViewById(R.id.bottom_navigation_view);
        if (bottomNavigationView == null) {
            throw new RuntimeException("BottomNavigationView not found in layout");
        }
    }

    /**
     * 设置导航组件
     */
    private void setupNavigation() {
        // 获取NavHostFragment
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment_activity_main);

        if (navHostFragment == null) {
            Log.e(TAG, "NavHostFragment not found!");
            throw new RuntimeException("NavHostFragment not found in layout");
        }

        navController = navHostFragment.getNavController();

        // 配置AppBarConfiguration
        appBarConfiguration = new AppBarConfiguration.Builder(TOP_LEVEL_DESTINATIONS)
                .build();

        // 设置ActionBar与导航同步
        if (getSupportActionBar() != null) {
            NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        }

        // 将BottomNavigationView与NavController关联
        NavigationUI.setupWithNavController(bottomNavigationView, navController);
        
        // 设置导航监听器
        setupNavigationListener();
    }

    /**
     * 设置导航变化监听器
     */
    private void setupNavigationListener() {
        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            int destId = destination.getId();
            String destinationName = getResources().getResourceEntryName(destId);
            Log.d(TAG, "Navigated to: " + destinationName);
            
            // 根据目标页面决定是否显示返回按钮
            boolean isTopLevel = isTopLevelDestination(destId);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(!isTopLevel);
            }
        });
    }

    /**
     * 检查是否为顶级目标页面
     * @param destinationId 目标页面ID
     * @return true if top level destination
     */
    private boolean isTopLevelDestination(int destinationId) {
        for (int topLevelId : TOP_LEVEL_DESTINATIONS) {
            if (topLevelId == destinationId) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理返回按钮点击事件
     */
    @Override
    public boolean onSupportNavigateUp() {
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    /**
     * 处理选项菜单项点击
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 首先让当前Fragment处理菜单项
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment_activity_main);
        
        if (navHostFragment != null) {
            androidx.fragment.app.Fragment currentFragment = navHostFragment.getChildFragmentManager()
                    .getPrimaryNavigationFragment();
            
            if (currentFragment != null && currentFragment.onOptionsItemSelected(item)) {
                return true;
            }
        }
        
        // 然后尝试Navigation处理
        try {
            if (NavigationUI.onNavDestinationSelected(item, navController)) {
                return true;
            }
        } catch (IllegalArgumentException e) {
            // 如果Navigation找不到对应的action，忽略错误继续处理
            Log.d(TAG, "Navigation action not found for menu item: " + item.getTitle());
        }
        
        return super.onOptionsItemSelected(item);
    }

    /**
     * 处理返回键按下事件
     */
    @Override
    public void onBackPressed() {
        // 如果当前不在顶级页面，使用导航返回
        if (!isTopLevelDestination(navController.getCurrentDestination().getId())) {
            if (!navController.popBackStack()) {
                super.onBackPressed();
            }
        } else {
            // 在顶级页面时，正常处理返回键
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "MainActivity destroyed");
    }
    
    /**
     * 导航到番茄钟页面
     */
    public void navigateToPomodoro() {
        if (navController != null) {
            try {
                navController.navigate(R.id.navigation_pomodoro);
            } catch (Exception e) {
                Log.e(TAG, "Navigation to pomodoro failed", e);
                // 如果番茄钟页面不存在，先跳转到任务页面
                navController.navigate(R.id.navigation_tasks);
            }
        }
    }
    
    /**
     * 导航到健康页面  
     */
    public void navigateToHealth() {
        if (navController != null) {
            try {
                navController.navigate(R.id.navigation_health);
            } catch (Exception e) {
                Log.e(TAG, "Navigation to health failed", e);
                // 如果健康页面不存在，显示提示
                showToast("健康页面开发中");
            }
        }
    }
    
    /**
     * 导航到轮盘页面
     */
    public void navigateToRoulette() {
        if (navController != null) {
            try {
                navController.navigate(R.id.navigation_roulette);
            } catch (Exception e) {
                Log.e(TAG, "Navigation to roulette failed", e);
                showToast("轮盘功能开发中");
            }
        }
    }
    
    /**
     * 显示Toast提示
     */
    private void showToast(String message) {
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show();
    }

    /**
     * 初始化任务完成通知器
     */
    private void initializeTaskCompletionNotifier() {
        try {
            com.example.managemyself.util.TaskCompletionNotifier taskCompletionNotifier = 
                com.example.managemyself.util.TaskCompletionNotifier.getInstance();
            taskCompletionNotifier.init(this);
            Log.d(TAG, "TaskCompletionNotifier initialized");
        } catch (Exception e) {
            Log.e(TAG, "Failed to initialize TaskCompletionNotifier", e);
        }
    }
} 